package com.powernode.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.config.WhiteUrlsConfig;
import com.powernode.constant.AuthConstants;
import com.powernode.constant.BussinessEnum;
import com.powernode.constant.HttpConstants;
import com.powernode.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;


/**
 * 全局token过滤器
 */
@Component
@Slf4j
public class AuthFilter implements GatewayFilter, Ordered {
    @Autowired
    private WhiteUrlsConfig whiteUrlsConfig;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 过滤器核心方法
     * 获取请求路径
     * 判断请求路径是否可以放行
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取请求路径
        String path=request.getPath().toString();
        //判断路径是否可以放行
        if(whiteUrlsConfig.getAllowUrls().contains(path)){
            return chain.filter(exchange);
        }
        String authorizationValue=request.getHeaders().getFirst(AuthConstants.AUTHORIZATION);
        //判断是否有值
        if (StringUtils.hasText(authorizationValue)){
            //获取token
            String token=authorizationValue.replaceFirst(AuthConstants.BEARER,"");
            //判断token是否有值且是否存在redis中
            if (StringUtils.hasText(token) && stringRedisTemplate.hasKey(AuthConstants.LOGIN_TOKEN_PREFIX+token)){
                //放行
                return chain.filter(exchange);
            }
        }
        log.error("拦截非法请求，时间:{}，请求api路径:{}",new Date(),path);
        //获取相应对象
        ServerHttpResponse response = exchange.getResponse();
        //设置响应头信息
        response.getHeaders().set(HttpConstants.CONTENT_TYPE,HttpConstants.APPLICATION_JSON);
        //设置响应消息
        Result<Object> result = Result.fail(BussinessEnum.UN_AUTHORIZATION);
        //创建一个objectmapper对象
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = new byte[0];
        try {
            bytes = objectMapper.writeValueAsBytes(result);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return -5;
    }
}
